package com.zdp.springcloud.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.zdp.springcloud.domain.CommonResult;
import com.zdp.springcloud.domain.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.client.RestTemplate;

/**
 * @author sesshomaru
 * @date 2019/12/5 16:13
 */
@Service
public class UserService {
    private Logger LOGGER = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private RestTemplate restTemplate;

    @Value("${service-url.user-service}")
    private String userServiceUrl;

/*  fallbackMethod：指定服务降级处理方法；
    ignoreExceptions：忽略某些异常，不发生服务降级；
    commandKey：命令名称，用于区分不同的命令；
    groupKey：分组名称，Hystrix会根据不同的分组来统计命令的告警及仪表盘信息；
    threadPoolKey：线程池名称，用于划分线程池。*/
    @HystrixCommand(fallbackMethod = "getDefaultUser")
    public CommonResult getUser(Long id){
        CommonResult result = restTemplate.getForObject(userServiceUrl + "/user/{1}", CommonResult.class, id);
        return result;
    }

    @HystrixCommand(fallbackMethod = "getDefaultUser",
            commandKey = "getUserCommand",
            groupKey = "getUserGroup",
    threadPoolKey = "getUserThreadPool")
    public CommonResult getUserCommand(Long id){
        return restTemplate.getForObject(userServiceUrl + "/user/{1}", CommonResult.class, id);
    }

    public CommonResult getDefaultUser(@PathVariable Long id) {
        User defaultUser = new User(-1L, "defaultUser", "123456");
        LOGGER.error("服务发生降级处理...");
        return new CommonResult<>(defaultUser);
    }

    //===================测试指定异常服务降级=================
    @HystrixCommand(fallbackMethod = "getDefaultUser2",ignoreExceptions = {NullPointerException.class})
    public CommonResult getUserException(Long id){
        if(id == 1){
            throw new IndexOutOfBoundsException();
        } else if (id == 2){
            throw new NullPointerException();
        }
        return restTemplate.getForObject(userServiceUrl + "/user/{1}",CommonResult.class,id);
    }

    public CommonResult getDefaultUser2(@PathVariable Long id, Throwable e){
        User defaultUser = new User(-2L, "defaultUser", "123456");
        LOGGER.error("服务发生降级处理...");
        return new CommonResult<>(defaultUser);
    }


}
